package com.example.finalwork.pojo

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class GameViewModel : ViewModel() {
    var state by mutableStateOf(GameState())

    val boardItems: MutableMap<Int, BoardCellValue> = mutableMapOf(
        1 to BoardCellValue.NONE,
        2 to BoardCellValue.NONE,
        3 to BoardCellValue.NONE,
        4 to BoardCellValue.NONE,
        5 to BoardCellValue.NONE,
        6 to BoardCellValue.NONE,
        7 to BoardCellValue.NONE,
        8 to BoardCellValue.NONE,
        9 to BoardCellValue.NONE
    )

    fun onAction(action: UserActions) {
        when (action) {
            is UserActions.BoardTapped -> {
                addValueToBoard(action.cellNo)

            }

            UserActions.PlayAgainButtonClicked -> {
                gameReset()
            }
        }
    }

    private fun gameReset() {
        boardItems.forEach{(i,_) ->
            boardItems[i] = BoardCellValue.NONE
        }
        state = state.copy(
            hintText = "圈方先手",
            currentTurn = BoardCellValue.CIRCLE,
            victoryType = VictoryType.NONE,
            hasWon = false
        )
    }

    private fun addValueToBoard(cellNo: Int) {
        if (boardItems[cellNo] != BoardCellValue.NONE || state.isGameOver) {
            return // 如果游戏已结束，或者该格子已被点击，则不执行任何操作。
        }

        if (state.currentTurn == BoardCellValue.CIRCLE) {
            boardItems[cellNo] = BoardCellValue.CIRCLE
            if (checkForVictory(BoardCellValue.CIRCLE)) {
                state = state.copy(
                    hintText = "圈方获胜",
                    playerCircleCount = state.playerCircleCount + 1,
                    hasWon = true,
                    isGameOver = true, // 设置游戏结束
                    nextTurn = BoardCellValue.CROSS // 设置下回合由叉方先手
                )
                viewModelScope.launch {
                    delay(3000)
                    gameResetWithIncrement()
                }
            } else if (hasBoardFull()) {
                state = state.copy(
                    hintText = "平局",
                    drawCount = state.drawCount + 1,
                    isGameOver = true // 设置游戏结束
                )
                viewModelScope.launch {
                    delay(3000)
                    gameResetWithIncrement()
                }
            } else {
                state = state.copy(
                    hintText = "轮到叉方",
                    currentTurn = BoardCellValue.CROSS // 当前转变为叉方
                )
            }

        } else if (state.currentTurn == BoardCellValue.CROSS) {
            boardItems[cellNo] = BoardCellValue.CROSS
            if (checkForVictory(BoardCellValue.CROSS)) {
                state = state.copy(
                    hintText = "叉方获胜",
                    playerCrossCount = state.playerCrossCount + 1,
                    hasWon = true,
                    isGameOver = true, // 设置游戏结束
                    nextTurn = BoardCellValue.CIRCLE // 设置下回合由圈方先手
                )
                viewModelScope.launch {
                    delay(3000)
                    gameResetWithIncrement()
                }
            } else if (hasBoardFull()) {
                state = state.copy(
                    hintText = "平局",
                    drawCount = state.drawCount + 1,
                    isGameOver = true // 设置游戏结束
                )
                viewModelScope.launch {
                    delay(3000)
                    gameResetWithIncrement()
                }
            } else {
                state = state.copy(
                    hintText = "轮到圈方",
                    currentTurn = BoardCellValue.CIRCLE // 当前转变为圈方
                )
            }
        }
    }

    // 修改重置游戏的方法，设置下回合的先手
    private fun gameResetWithIncrement() {
        boardItems.forEach { (i, _) ->
            boardItems[i] = BoardCellValue.NONE
        }
        state = state.copy(
            hintText = "轮到 ${if (state.nextTurn == BoardCellValue.CIRCLE) "圈方" else "叉方"} 先手",
            currentTurn = state.nextTurn, // 根据之前设置的 nextTurn 进行调整
            victoryType = VictoryType.NONE,
            hasWon = false,
            isGameOver = false // 重启时设置为 false
        )
        
    }

    private fun checkForVictory(boardValue: BoardCellValue): Boolean {
        when{
            boardItems[1] == boardValue && boardItems[2] == boardValue && boardItems[3] == boardValue -> {
                state = state.copy(victoryType = VictoryType.HORIZONTAL1)
                return true
            }
            boardItems[4] == boardValue && boardItems[5] == boardValue && boardItems[6] == boardValue -> {
                state = state.copy(victoryType = VictoryType.HORIZONTAL2)
                return true
            }
            boardItems[7] == boardValue && boardItems[8] == boardValue && boardItems[9] == boardValue -> {
                state = state.copy(victoryType = VictoryType.HORIZONTAL3)
                return true
            }
            boardItems[1] == boardValue && boardItems[4] == boardValue && boardItems[7] == boardValue -> {
                state = state.copy(victoryType = VictoryType.VERTICAL1)
                return true
            }
            boardItems[2] == boardValue && boardItems[5] == boardValue && boardItems[8] == boardValue -> {
                state = state.copy(victoryType = VictoryType.VERTICAL2)
                return true
            }
            boardItems[3] == boardValue && boardItems[6] == boardValue && boardItems[9] == boardValue -> {
                state = state.copy(victoryType = VictoryType.VERTICAL3)
                return true
            }
            boardItems[1] == boardValue && boardItems[5] == boardValue && boardItems[9] == boardValue -> {
                state = state.copy(victoryType = VictoryType.DIAGONAL1)
                return true
            }
            boardItems[3] == boardValue && boardItems[5] == boardValue && boardItems[7] == boardValue -> {
                state = state.copy(victoryType = VictoryType.DIAGONAL2)
                return true
            }
            else -> {
                return false
            }
        }
    }

    private fun hasBoardFull(): Boolean {
        if(boardItems.containsValue(BoardCellValue.NONE)){
            return false
        }
        return true
    }
}